package cn.sinokj.party.chineseFourParty.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.IndexImageWebActivity;
import cn.sinokj.party.chineseFourParty.activity.MainActivity;
import cn.sinokj.party.chineseFourParty.adapter.ImportantNewsListAdapter;
import cn.sinokj.party.chineseFourParty.adapter.XListAdapter;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.IndexImage;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.view.xlist.XListView;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 重要新闻Fragment
 */

public class ImportantNewsFragment extends BaseFragment {
    public static final int TO_CHANGE_READ_STATUS = 3;
    private static final int REFRESH = 0;
    private static final int INIT_DATA = 1;
    private static final int LOAD_MORE = 2;
    private static final int QUERY_SIZE = 10;
    private MainActivity activity;
    private int nPage = 1;
    private IndexImage indexImage;
    private ImportantNewsListAdapter xListAdapter;
    private List<IndexImage> dataList = new ArrayList<IndexImage>();
    @BindView(R.id.xlist_listview)
    public XListView dataListView;
    private boolean isInit;
    private boolean isLoad;
    private boolean loginIsRush = false;
    /*Tag的Id*/
    private int nId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_important_news, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isInit = true;
        activity = (MainActivity) getActivity();
        dataListView.setXListViewListener(ixListViewListener);
        dataListView.setOnItemClickListener(onItemClickListener);
        //isCanLoadData();
        new Thread(new LoadDataThread(INIT_DATA)).start();
    }


    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // XListView 默认position为1
            indexImage = dataList.get(position - 1);
            Intent intent = new Intent(activity, IndexImageWebActivity.class);
            intent.putExtra("url", indexImage.url);
            intent.putExtra("icon", indexImage.vcPath);
            intent.putExtra("topTitle", "要闻");
            intent.putExtra("nShared", indexImage.nShared);
            intent.putExtra("describe", indexImage.vcDescribe);
            intent.putExtra("isRush", true);
            startActivity(intent);
        }
    };

    private XListView.IXListViewListener ixListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            nPage = 1;
            // DialogShow.showRoundProcessDialog(activity);
            new Thread(new LoadDataThread(REFRESH)).start();
        }

        @Override
        public void onLoadMore() {
            nPage += 1;
            new Thread(new LoadDataThread(LOAD_MORE)).start();
        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isCanLoadData();
    }


    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            lazyLoad();
            isLoad = true;
        } else {
            if (isLoad) {

            }
        }
    }


    private void lazyLoad() {
        //DialogShow.showRoundProcessDialog(activity);
        new Thread(new LoadDataThread(INIT_DATA)).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        isInit = false;
        isLoad = false;
    }


    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        if (getUserVisibleHint()) {
            if (what == TO_CHANGE_READ_STATUS) {
                if (indexImage != null) {
                    return HttpDataService.getSingleReadStatus(String.valueOf(indexImage.nId));
                }else {
                    return null;
                }
            }
        }
        //Log.e("wsj--", nId + "");
        return HttpDataService.getNews("首页广告", String.valueOf(nPage), String.valueOf(QUERY_SIZE),
                App.nCommitteeId, nId + "");
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        if (msg.what == TO_CHANGE_READ_STATUS) {
            indexImage.nStatus = (jsonObject.optInt(HttpConstants.RESULT));
            indexImage.nclick = Integer.valueOf(jsonObject.optString("nClick"));
            xListAdapter.notifyDataSetChanged();
            return;
        }
        JSONArray jsonArray = jsonObject.optJSONArray(HttpConstants.OBJECTS);
        List<IndexImage> list = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<IndexImage>>() {
                }.getType());
        // DialogShow.closeDialog();
        switch (msg.what) {
            case REFRESH:
                dataListView.stopRefresh();
                dataList = new ArrayList<IndexImage>();
            case INIT_DATA:
                /*if (list.size() == 0 && getUserVisibleHint()) {
                    Log.e("wsj---", "22222222222" + getUserVisibleHint());
                    Toast.makeText(activity, "没有查到相关信息", Toast.LENGTH_SHORT).show();
                }*/
                dataList.clear();
                dataList.addAll(list);
                xListAdapter = new ImportantNewsListAdapter(activity, dataList);
                dataListView.setAdapter(xListAdapter);
                break;
            case LOAD_MORE:
                dataList.addAll(list);
                xListAdapter.notifyDataSetChanged();
                break;

        }
        dataListView.setPullLoadEnable(list.size() == QUERY_SIZE);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case 001:
                new Thread(new LoadDataThread(TO_CHANGE_READ_STATUS)).start();
                break;
        }
    }

    public void setNclass(int nId) {
        this.nId = nId;
    }
}
